package com.tech.thread.juc;

/**
 * @Description:
 * @Author: zl
 * @Date: 2019/7/25 10:53
 */

import java.util.concurrent.CountDownLatch;

/**
 * <p>Title: JUC_CountDownLatch_Test </p>
 * <p>Description:
 * 当前示例：用主线程统计多个线程执行时间
 * </p>
 * Date: 2017年7月22日上午5:45:29
 *
 * @author zl
 * @version 1.0
 * Significant Modify：
 * Date Author Content
 * ==========================================================
 * 2017年7月22日 zl 创建文件,实现基本功能
 * <p>
 * ==========================================================
 */
public class JUC_CountDownLatch_Test {

    public static void main(String[] args) {
        //1、计算线程在通过等待之前需要被调用的次数。
        CountDownLatch latch = new CountDownLatch(10);
        CountDownLatchTest01 latchTest = new CountDownLatchTest01(latch);
        long t1 = System.currentTimeMillis();
        for (int i = 0; i < 10; i++) {
            new Thread(latchTest).start();
        }
        try {
            latch.await();
        } catch (Exception e) {
        }
        long t2 = System.currentTimeMillis();
        System.out.println("线程执行时间" + (t2 - t1));
    }

}

//统计时间
class CountDownLatchTest01 implements Runnable {

    private CountDownLatch latch;
    public CountDownLatchTest01(CountDownLatch latch) {
        this.latch = latch;
    }

    @Override
    public void run() {
        try {
            Thread.sleep(1000);
            System.out.println(Thread.currentThread().getName() + ":睡眠结束");
        } catch (InterruptedException e) {
            e.printStackTrace();
        } finally {
            //减少锁存器的计数，如果计数达到零，释放所有等待的线程。
            latch.countDown();
        }
    }
}
